package file;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * This class is responsible for writing the debugging log to a file.
 * 
 * @author Kyle_Solo
 */
public class Logger extends PrintStream {

	/**
	 * @return the name of a log file that should be created
	 */
	public static File getLogFile() {
		Date date = new Date();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd-");
		int num = 0;
		String name;
		File file;
		do {
			name = df.format(date) + num + ".log";
			file = new File(name);
			num++;
		} while (file.exists());
		return file;
	}

	/**
	 * @return a time prefix, prepended to all output
	 */
	private static String prefix() {
		Date date = new Date();
		DateFormat dtf = new SimpleDateFormat("HH:mm:ss");
		return "[" + dtf.format(date) + "]: ";
	}

	/**
	 * Creates a new logger, giving it an unique filename to save log data.
	 * 
	 * @throws FileNotFoundException
	 */
	public Logger() throws FileNotFoundException {
		super(new BufferedOutputStream(new FileOutputStream(getLogFile(), true)));
		// currently could append to the file, but is given a non-existing file each time
		// could someday have a log file for each game that persists between saves
	}

	@Override
	public void println() {
		super.println();
		super.flush();
	}

	@Override
	public void println(boolean x) {
		super.println(prefix() + x);
		super.flush();
	}

	@Override
	public void println(char x) {
		super.println(prefix() + x);
		super.flush();
	}

	@Override
	public void println(char[] x) {
		String s = new String(x);
		super.println(prefix() + s);
		super.flush();
	}

	@Override
	public void println(double x) {
		super.println(prefix() + x);
		super.flush();
	}

	@Override
	public void println(float x) {
		super.println(prefix() + x);
		super.flush();
	}

	@Override
	public void println(int x) {
		super.println(prefix() + x);
		super.flush();
	}

	@Override
	public void println(long x) {
		super.println(prefix() + x);
		super.flush();
	}

	@Override
	public void println(Object x) {
		super.println(prefix() + x);
		super.flush();
	}

	@Override
	public void println(String x) {
		super.println(prefix() + x);
		super.flush();
	}
}
